﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using IceDog.EFCore.ContosoUniversity.Data;
using IceDog.EFCore.ContosoUniversity.Models;
using IceDog.EFCore.ContosoUniversity.Models.SchoolViewModels;

namespace IceDog.EFCore.ContosoUniversity.Pages.Instructors
{
    public class IndexModel : PageModel
    {
        private readonly IceDog.EFCore.ContosoUniversity.Data.SchoolContext _context;

        public IndexModel(IceDog.EFCore.ContosoUniversity.Data.SchoolContext context)
        {
            _context = context;
        }
        
        public InstructorIndexData IndexData { get; set; }
        public int InstructorID { get; set; }
        public int CourseID { get; set; }

        public async Task OnGetAsync(int? id, int? courseID)
        {
            IndexData = new InstructorIndexData();
            IndexData.Instructors = await _context.Instructors
                  .Include(i => i.OfficeAssignment)
                  .Include(i => i.CourseAssignments)
                    .ThenInclude(i => i.Course)
                        .ThenInclude(c=>c.Department)//根据课程分配表查找相关课程对应的系别
                  //.Include(i => i.CourseAssignments)
                  //      .ThenInclude(i => i.Course)
                  //          .ThenInclude(i => i.Enrollments)
                  //              .ThenInclude(i => i.Student)//根据课程分配包查找相关课程的登记情况，然后根据登记情况查询相关的学生
                  //.AsNoTracking() //为了后续数据加载操作，要注释掉
                  .OrderBy(i => i.LastName)
                  .ToListAsync();
            if (id != null)
            {
                InstructorID = id.Value;
                Instructor instructor = IndexData.Instructors.Single(i => i.ID == id.Value);
                IndexData.Courses = instructor.CourseAssignments.Select(s => s.Course);
            }
            if (courseID != null)
            {
                CourseID = courseID.Value;
                var selectedCourse = IndexData.Courses.Single(x => x.CourseID == courseID);
                await _context.Entry(selectedCourse).Collection(x => x.Enrollments).LoadAsync();//根据课程分配表查找相关课程对应的系别
                foreach (Enrollment enrollment in selectedCourse.Enrollments)
                {
                    await _context.Entry(enrollment).Reference(x => x.Student).LoadAsync();//根据登记情况查询相关的学生 
                }
                IndexData.Enrollments = selectedCourse.Enrollments;
            }
        }
    }
}
